package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * mapper xml 文件解析类
 *
 * @author Tengfei.Wang
 * @date 26/8/2020
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream resourceAsStream) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document mapperDocument = saxReader.read(resourceAsStream);
        Element mapper = mapperDocument.getRootElement();
        String namespace = mapper.attributeValue("namespace");
        //获取mapper中需要执行的语句并写入到Configuration中
        List<Element> selectList = mapper.selectNodes("//select");
        List<Element> insertList = mapper.selectNodes("//insert");
        selectList.addAll(insertList);
        List<Element> updateList = mapper.selectNodes("//update");
        selectList.addAll(updateList);
        List<Element> deleteList = mapper.selectNodes("//delete");
        selectList.addAll(deleteList);
        setMappedStatement(namespace, selectList, configuration);
    }

    private void setMappedStatement(String namespace, List<Element> selectList, Configuration configuration) {
        for (Element element : selectList) {
            MapperStatement mappedStatement = new MapperStatement();
            String id = element.attributeValue("id");
            mappedStatement.setId(namespace + "." + id);
            try {
                String parameterType = element.attributeValue("parameterType");
                if (parameterType != null && !"".equals(parameterType)) {
                    Class<?> parameterClass = Class.forName(parameterType);
                    mappedStatement.setParameterType(parameterClass);
                }

                String resultType = element.attributeValue("resultType");
                if (resultType != null && !"".equals(resultType)) {
                    Class<?> resultClass = Class.forName(resultType);
                    mappedStatement.setResultType(resultClass);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            mappedStatement.setSql(element.getStringValue());

            configuration.getStatementMap().put(mappedStatement.getId(), mappedStatement);
        }
    }
}
